﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FileDFS.Model;
using FileDFS.Utils;
using System.IO;
using System.Drawing;
using FileDFS.Utils.PathConfig;
/*
 * Coder:Tieria
 * WriteTime:2015.2.26
 * FileName:ImageHandler.cs
 * ReMark:图片操作相关
 */
namespace FileDFS.Bll
{
    public class ImageHandler
    {
        public static ImageHandler GetInstance()
        {
            return new ImageHandler();
        }

        #region 保存每一张图片,并且按照参数生成每张图片的缩略图
        /// <summary>
        /// 保存每一张原图,并且,生成每张图片的缩略图
        /// </summary>
        /// <param name="uploadModel"></param>
        /// <returns></returns>
        public ImageResultBody SaveImage(ImageUploadModel uploadModel)
        {
            ImageResultBody resultBody = new ImageResultBody()
            {
                Id = uploadModel.Id
            };
            try
            {
                string imageName = AlgorithmHelper.GetGuid() + "." + uploadModel.ImageExtension.ToString();
                #region 当前的虚拟路径和绝对路径
                Utils.PathConfig.PathDetail currentPath;
                if (uploadModel.IsPublic)
                {
                    currentPath = Utils.PathConfig.CatalogHandler.GetInstance().GetCurrentPath(OptionGetEnum.ImagePublic);
                }
                else
                {
                    currentPath = Utils.PathConfig.CatalogHandler.GetInstance().GetCurrentPath(OptionGetEnum.ImagePrivate);
                }
                #endregion
                //Utils.TestLog.Logger(PathHelper.CombineRelativePath(currentPath.Virtual_FullPath, imageName));

                //虚拟全路径，带文件名称和扩展名
                resultBody.ImageFullPath = PathHelper.CombineRelativePath(currentPath.Virtual_FullPath, imageName);

                //将原图的图片流转换成图片
                System.Drawing.Image originalImage = Image.FromStream(uploadModel.DataSource);
                // System.Drawing.Image originalImage = Image.FromStream(uploadModel.DataSource);
                //保存原图
                originalImage.Save(Path.Combine(currentPath.Absolute_FullPath, imageName));
                //如果该图片有生成缩略图,则进行裁剪,并生成
                if (uploadModel.CreateThumbnail)
                {
                    List<ThumbnailResult> thumbnailList = new List<ThumbnailResult>();

                    foreach (var thumbnailDetail in uploadModel.ThumbnailList)
                    {
                        thumbnailList.Add(ImageHelper.GetInstance().CutToThumbnail(originalImage, thumbnailDetail, currentPath));
                    }
                    resultBody.ThumbnailResult = thumbnailList;
                }

            }
            catch (Exception ex)
            {
                Utils.TestLog.Logger(ex.Message);
            }

            return resultBody;
        }

        #endregion

    }
}
